package net.xdclass.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.CouponRecordMessage;
import net.xdclass.service.CouponRecordService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * @Classname CouponMqListener
 * @Description TODO
 * @Date 2022/5/13 17:20
 * @Created by sunhao
 */
@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.coupon_release_queue}")
public class CouponMqListener {

  @Autowired
  private CouponRecordService couponRecordService;

  @Autowired
  private RedissonClient redissonClient;

  @RabbitHandler
  public void releaseCouponRecord(CouponRecordMessage recordMessage, Message message, Channel channel) throws IOException {
    log.info("监听到消息 releaseCouponRecord{}", recordMessage);
    RLock lock = redissonClient.getLock(String.format("lock:coupon_record_release:%s", recordMessage.getTaskId()));
    lock.lock();
    long msgTag = message.getMessageProperties().getDeliveryTag();
    boolean flag = couponRecordService.releaseCouponRecord(recordMessage);
    try {
      if (flag) {
        //消息消费成功 确认ACK
        log.info("消息消费成功 确认ACK{}", recordMessage);
        channel.basicAck(msgTag, false);
      } else {
        //消息消费失败 重新入队
        log.info("消息消费失败 重新入队{}", recordMessage);
        channel.basicReject(msgTag, true);
      }
    } catch (IOException e) {
      log.info("消息消费异常{} 重新入队{}", e, recordMessage);
      channel.basicReject(msgTag, true);
    }finally {
      lock.unlock();
    }
  }

}
